package com.bsj.power.pls.config.net.netty.common;

import com.alibaba.fastjson.JSON;
import com.bsj.consumerQ.until.ExceptionUntil;
import com.bsj.power.pls.config.net.netty.AnalysisData;
import com.bsj.power.pls.config.net.netty.TcpSerUntil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author yinhao
 * @version 1.0
 * @description 数据解析
 * @date 2024/9/23
 */
@ChannelHandler.Sharable
@Slf4j
public class HandleUWB extends SimpleChannelInboundHandler<Object> {

    static private ChannelHandlerContext myCtx;

    private AnalysisData analysisData;

    public HandleUWB(AnalysisData now) {
        this.analysisData = now;
    }

    /**
     * 变为字节数据
     * @param msg
     * @return
     */
    private byte[] changeBytes(Object msg) {
        byte[] array = null;
        try {
            array = (byte[]) msg;
        } catch (ClassCastException e) {
            log.error("Data conversion error: {}", ExceptionUntil.getErrorStr(e));
            return null;
        }
        return array;
    }

    /**
     * 发送返回数据
     * @param ctx
     * @param replyArray
     */
    private void sendReply(ChannelHandlerContext ctx, byte[] replyArray) {
        if (replyArray != null) {
            TcpSerUntil.send(ctx, replyArray);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
        //转变为数据
        byte[] bytes = changeBytes(o);
        if (bytes == null) {
            return;
        }
        //获得的数据源
        analysisData.analysis(bytes);
    }

    /**
     * 未处理的异常都会在这里
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (!cause.getLocalizedMessage().equals("Connection reset by peer")) {
            log.error("Proc exceptionCaught: {}", ExceptionUntil.getErrorStr(cause));
        }
    }

    /**
     * 新的客户端连接上来了
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        myCtx = ctx;
        super.channelActive(ctx);
    }

    /**
     * 客户端连接关闭
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }
}
